import MarkdownIt from 'markdown-it'
import container from 'markdown-it-container'
import hljs from 'highlight.js'

const mdi = new MarkdownIt({
  html: true,
  linkify: true,
  breaks: true,
  highlight(str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs"><code>${hljs.highlight(str, { language: lang }).value}</code></pre>`
      } catch {}
    }
    return `<pre class="hljs"><code>${hljs.highlightAuto(str).value}</code></pre>`
  },
})

mdi.use(container, 'think', {
  render(tokens, idx) {
    const token = tokens[idx]
    if (token.nesting === 1) {
      return `
<details open style="margin-bottom:1rem; max-width:100%; word-break:break-word;">
  <summary style="font-size:14px; color:#9ca3af; cursor:default; margin-left:0.5rem;">思考</summary>
  <div style="margin-top:0.25rem; font-size:14px; color:#6b7280; border-left:2px solid #d1d5db; padding-left:0.75rem; margin-left:0.75rem;">
`
    } else {
      return `
  </div>
</details>
`
    }
  },
})

export function renderMarkdown(input) {
  // 把 <think> 标签转成 :::think 容器
  const normalized = input.replace(/<think>/gi, ':::think\n').replace(/<\/think>/gi, '\n:::')
  return mdi.render(normalized)
}
